#region Copyright
/// <copyright>
/// Copyright (c) 2007 Ilia Shramko.
/// Released under the terms of the GNU General Public License.
/// </copyright>
#endregion

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace Osh.Dvb
{
	/// <summary>
	/// PsiSectionStream class provides packetized access to a continuous PSI section stream.
	/// </summary>
	public class PsiSectionStream : PacketStream
	{
		private Stream _sourceStream;

		/// <summary>
		/// Constructs PSI section stream.
		/// </summary>
		/// <param name="stream">Continuous stream of PSI sections following one after enother. 
		/// Stream must not include pointer_field or stuffing bytes (0xFF) from the TS.</param>
		public PsiSectionStream(Stream stream)
		{
			if(stream == null)
				throw new ArgumentNullException("stream");
			_sourceStream = stream;
		}

		protected override bool MoveToNextPacketInternal()
		{
			int byte0 = _sourceStream.ReadByte(); // tableId
			if(byte0 == -1)
				return false;

			int byte1 = _sourceStream.ReadByte();
			int byte2 = _sourceStream.ReadByte();

			int sectionLength = ((byte1 & 0xF) << 8) + byte2;
			this.PacketSize = 3 + sectionLength;

			EnsurePacketBufferSize(this.PacketSize);

			this.PacketBuffer[0] = (byte)byte0;
			this.PacketBuffer[1] = (byte)byte1;
			this.PacketBuffer[2] = (byte)byte2;

			int numBytesRead = 0;
			if(sectionLength > 0)
				numBytesRead = _sourceStream.Read(this.PacketBuffer, 3, sectionLength); // TODO: make a loop

			if(numBytesRead < sectionLength)
				return false;

			return true;
		}

		public override void Close()
		{
			base.Close();
			_sourceStream.Close();
		}
	}
}
